package com.wngbms.netty._11tcp_perfect.client;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.nio.charset.Charset;
import java.util.UUID;

public class MyClientHandler extends SimpleChannelInboundHandler<ClientMsgEntity> {
    int count;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ClientMsgEntity msg) throws Exception {
        int len = msg.getLen();
        byte[] content = msg.getContent();

        System.out.println("客户端接收到消息如下");
        System.out.println("长度=" + len);
        System.out.println("内容=" + new String(content, Charset.forName("utf-8")));

        System.out.println("客户端接收消息数量=" + (++this.count));

        System.out.println();
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {

        for (int i = 0; i < 15; i++) {
            String mes = "今天天气冷，吃火锅-" + UUID.randomUUID().toString();
            byte[] content = mes.getBytes(Charset.forName("utf-8"));
            int length = mes.getBytes(Charset.forName("utf-8")).length;

            ClientMsgEntity clientMsgEntity = new ClientMsgEntity();
            clientMsgEntity.setLen(length);
            clientMsgEntity.setContent(content);

            ctx.writeAndFlush(clientMsgEntity);
        }

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
